package me.gm.stcont;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;

public class Utils {

	private static Logger logger = Logger.getLogger(Utils.class);

	private static Md5PasswordEncoder passwordEncoder;

	public static String encodePassword(String password) {
		logger.debug("started encodePassword");

		if (passwordEncoder == null) {
			passwordEncoder = new Md5PasswordEncoder();
		}

		logger.debug("finished encodePassword");

		return passwordEncoder.encodePassword(password, null);
	}

	public static String convertToUtf8(String from) {
		logger.debug("started convertToUtf8");

		String to;

		try {
			to = new String(from.getBytes(), "UTF-8");
		} catch (UnsupportedEncodingException exception) {
			if (logger.isEnabledFor(Level.ERROR)) {
				logger.error("error converting to UTF-8", exception);
			}

			to = "";
		}

		logger.debug("finished convertToUtf8");

		return to;
	}

	public static void addError(List<Error> errors, String type) {
		addError(errors, type, new String[0]);
	}

	public static void addError(List<Error> errors, String type,
			String... details) {
		Error error;

		error = new Error();
		error.setType(type);

		if (details.length > 0) {
			String key, value;

			Map<String, String> detailsNew;

			detailsNew = new HashMap<>();

			for (String detail : details) {
				key = detail.substring(0, detail.indexOf("="));
				value = detail.substring((detail.indexOf("=") + 1));

				detailsNew.put(key, value);
			}

			error.setDetails(detailsNew);
		}

		errors.add(error);
	}

}
